package com.tcm.logistics.service.logic.sf;

import com.alibaba.fastjson.JSON;
import com.base.core.lang.StringUtils;
import com.base.core.utils.JacksonUtils;
import com.base.core.utils.R;
import com.base.logistics.sf.bean.order.*;
import com.base.logistics.sf.bean.print.PrintSfPushRequest;
import com.base.logistics.sf.bean.print.PrintWaybillRequest;
import com.base.logistics.sf.bean.routes.SearchRoutesRequest;
import com.base.logistics.sf.bean.routes.SearchRoutesResponse;
import com.base.logistics.sf.request.SfOrderApiRequest;
import com.base.logistics.sf.request.SfPrintApiRequest;
import com.base.logistics.sf.request.SfRoutesApiRequest;
import com.base.logistics.utils.SfGsonBuilder;
import com.tcm.logistics.logic.sf.SfOrderLogicService;
import com.tcm.order.domain.dto.OrderDTO;
import com.tcm.order.service.OrderService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.List;

@DubboService(version = "0.0.1", delay = -1)
public class SfOrderLogicServiceImpl implements SfOrderLogicService {

    private static Log logger = LogFactory.getLog(SfOrderLogicServiceImpl.class);

    @Autowired
    private SfOrderApiRequest sfOrderApiRequest;

    @Autowired
    private SfRoutesApiRequest sfRoutesApiRequest;

    @Autowired
    private SfPrintApiRequest sfPrintApiRequest;

    @DubboReference(version = "0.0.1-alpha", timeout = 3000, check = false)
    private OrderService orderService;


    /**
     *
     * @param contactInfoList
     * @param cargoDetailList
     * @return
     */
    @Override
    public R createOrder(List<ContactInfo> contactInfoList, List<CargoDetail> cargoDetailList, String orderId, String remark) {
        try{
            CreateOrderRequest request = new CreateOrderRequest();
            request.setLanguage("zh-CN");
            request.setOrderId(orderId);
            request.setPayMethod(1);
            request.setRemark(remark);
            request.setContactInfoList(contactInfoList);
            request.setCargoDetails(cargoDetailList);
            CreateOrderResponse response = sfOrderApiRequest.createOrder(request);

            logger.info("【response】:"+SfGsonBuilder.create().toJson(response));
            return R.success(response);
        }catch (Exception e){
            e.printStackTrace();
            return R.fail(e.getMessage());
        }
    }

    @Override
    public R printData(String orderId,String searchType) {
        try{
            OrderRespRequest orderRespRequest = OrderRespRequest.builder()
                    .language("zh-cn").orderId(orderId).searchType(searchType).build();
            //获取订单寄收信息
            String deliveryInfo = orderService.findDeliveryInfoByOrderId(new Long(orderId));
            if(StringUtils.isBlank(deliveryInfo)){
                return R.fail("没有寄收人信息");
            }
            PrintWaybillRequest waybillRequest = JacksonUtils.toJavaObject(deliveryInfo,PrintWaybillRequest.class);
            boolean rs = sfPrintApiRequest.printData(orderRespRequest, waybillRequest);
            if(rs){
                return R.success();
            }
        }catch (Exception ex){
            return R.fail(ex.getMessage());
        }
        return R.fail();
    }

    @Override
    public R printPushPdf(PrintSfPushRequest request) {
        try{
            if (null == request.getMsgData()){
                return R.fail("未接收到数据");
            }
            String waybillNo = JSON.parseObject(request.getMsgData()).getString("waybillNo");
            if(StringUtils.isBlank(waybillNo)){
                return R.fail("运单号丢失");
            }
            String content = JSON.parseObject(request.getMsgData()).getString("content");
            final Base64.Decoder decoder = Base64.getDecoder();
            byte[] fileBytes= decoder.decode(content);
            //运单号作为文件名
            // 路径和文件名
            String fileName = "/home/zetikeji/workspace/html/pdf/" + waybillNo + ".pdf";
            // 使用Files.write创建一个文件并写入
            Files.write(Paths.get(fileName), fileBytes);
            System.out.println("请求报文===" + request.getMsgData());
            System.out.println("logisticID===" + request.getLogisticID());
            System.out.println("运单号===" + waybillNo);
            return R.success();
        }catch (Exception ex){
            return R.fail(ex.getMessage());
        }
    }

    @Override
    public R queryRoute(Integer trackingType, List<String> trackingNumber, Integer methodType) {
        try {
            SearchRoutesRequest routesRequest = new SearchRoutesRequest();
            routesRequest.setLanguage(0);
            routesRequest.setMethodType(methodType);
            routesRequest.setTrackingNumber(trackingNumber);
            routesRequest.setTrackingType(trackingType);
            SearchRoutesResponse response = sfRoutesApiRequest.searchRoutes(routesRequest);
            logger.info("【response】:" + SfGsonBuilder.create().toJson(response));
            return R.success(response);
        }catch (Exception ex){
            return R.fail(ex.getMessage());
        }
    }
}
